package com.zyasdk.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.annotation.SuppressLint;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.zyasdk.enums.AdType;
import com.zyasdk.interfaces.OnDLImageSuccessListener;
import com.zyasdk.model.Products;
import com.zyasdk.util.ZYALogUtils;
import com.zyasdk.util.StaticSetting;

@SuppressLint("DefaultLocale")
public class DLImage {
	ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);// 创建线程池，设定允许执行的最大线程数
	private Handler handler;
	private OnDLImageSuccessListener onDLImageSuccessListener;

	public void setOnDLImageSuccessListener(
			OnDLImageSuccessListener onDLImageSuccessListener) {
		this.onDLImageSuccessListener = onDLImageSuccessListener;
	}

	public DLImage(Handler handler) {
		this.handler = handler;
	}

	public void start(final Products ad, final AdType adType) {
		new AsyncTask<Void, Drawable, Drawable>() {

			@SuppressWarnings("deprecation")
			@Override
			protected Drawable doInBackground(Void... params) {
				Drawable drawable = null;
				try {

					if (ad == null || TextUtils.isEmpty(ad.getImgfile(adType))) {
						ZYALogUtils.e("url is null");
						if (onDLImageSuccessListener != null)
							onDLImageSuccessListener.success(null);
						return null;
					}
					String path = ad.getImgfile(adType);
					if (!path.toLowerCase().startsWith("http:")) {
						path = StaticSetting.FILE_SERVICEPATH
								+ ad.getImgfile(adType);
					}
					URL u = new URL(path);

					ZYALogUtils.e(u.toString());

					// 无内存卡直接将图片发送回去
					if (!Environment.getExternalStorageState().equals(
							Environment.MEDIA_MOUNTED)) {
						ZYALogUtils.e("no sdcard,send img");
						URLConnection connection = u.openConnection();
						drawable = new BitmapDrawable(
								BitmapFactory.decodeStream(connection
										.getInputStream()));
						if (drawable != null)
							return drawable;
					}
					File f = new File(getFilePath(ad.getImgfile(adType)));
					if (f.exists()) {
						ZYALogUtils.e("load local img");
						drawable = BitmapDrawable.createFromPath(getFilePath(ad
								.getImgfile(adType)));
						if (drawable != null)
							return drawable;
					}
					try {
						f.getParentFile().mkdirs();
						InputStream is = null;
						FileOutputStream fos = new FileOutputStream(
								getFilePath(ad.getImgfile(adType)));
						URLConnection connection = u.openConnection();
						is = connection.getInputStream();
						byte[] buf = new byte[1024];
						int len;
						while ((len = is.read(buf)) != -1) {
							fos.write(buf, 0, len);
						}
						fos.flush();
						is.close();
						fos.close();
						ZYALogUtils.e("load net img");
						drawable = BitmapDrawable.createFromPath(getFilePath(ad
								.getImgfile(adType)));
						if (drawable != null)
							return drawable;
					} catch (Exception e) {
						ZYALogUtils.e("no sdcard,send img");
						URLConnection connection = u.openConnection();
						drawable = new BitmapDrawable(
								BitmapFactory.decodeStream(connection
										.getInputStream()));
						if (drawable != null)
							return drawable;
					}

				} catch (Exception e) {
					e.printStackTrace();

				}
				return drawable;
			}

			@Override
			protected void onPostExecute(Drawable drawable) {
				if (drawable != null) {
					if (handler != null) {
						Message message = new Message();
						message.what = com.zyasdk.controll.WindowUtil.DOWNLOAD_IMAGE;
						Bundle bundle = new Bundle();
						bundle.putSerializable("product", ad);
						bundle.putSerializable("adType", adType);
						message.setData(bundle);
						message.obj = drawable;
						handler.sendMessage(message);
					}
				}
				if (onDLImageSuccessListener != null)
					onDLImageSuccessListener.success(drawable);
			}
		}.execute();
	}

	/**
	 * 获取图片在本地的路径
	 * 
	 * @param imageUrl
	 * @return
	 */
	public String getFilePath(String imageUrl) {
		// 截取图片名以及后缀
		String name = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
		// 根据名字获取指定目录下的文件
		File f = new File(Environment.getExternalStorageDirectory()
				.getAbsolutePath() + "/Download/Image/", name);
		return f.getAbsolutePath();
	}

	/**
	 * 获取Data目录
	 */
	public void getExternalStorage() {
		Environment.getDataDirectory();
	}

	/**
	 * 获取下载缓存目录
	 */
	public void getCacheStorage() {
		Environment.getDownloadCacheDirectory();
	}

}
